package part11singleton;

import java.lang.reflect.Constructor;

/**
 * @description: 静态内部类实现懒汉模式、线程安全、避免指令重排
 * 问题：会被反射破坏
 * @author: zhang hang
 * @date: 2024/3/24 14:27.
 * @version: 1.0
 */
public class SingletonTest05 {

    private SingletonTest05() {
        System.out.println(Thread.currentThread().getName() + "starting");
    }

    private static class SingletonInstance {
        private static final SingletonTest05 INSTANCE = new SingletonTest05();
    }

    public static SingletonTest05 getInstance() {
        return SingletonInstance.INSTANCE;
    }

    public static void main01(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                SingletonTest05.getInstance();
            }).start();
        }
    }

    // 反射破坏单例模式
    public static void main(String[] args) {
        try {
            SingletonTest05 singletonTest0501 = SingletonTest05.getInstance();
            Constructor<SingletonTest05> declaredConstructor = SingletonTest05.class.getDeclaredConstructor(null);
            declaredConstructor.setAccessible(true);
            SingletonTest05 singletonTest0502 = declaredConstructor.newInstance();
            System.out.println(singletonTest0501.hashCode());
            System.out.println(singletonTest0502.hashCode());
            System.out.println(singletonTest0501 == singletonTest0502);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
